package cn.xsshome.mvcdo.service;

import cn.xsshome.mvcdo.common.AIConstant;
import cn.xsshome.mvcdo.common.AipAdded;
import cn.xsshome.mvcdo.interceptor.BDFactory;
import cn.xsshome.mvcdo.pojo.ai.baidu.dbo.BDOCRGeneralDO;
import cn.xsshome.mvcdo.pojo.ai.baidu.po.BDOCRGeneralBean;
import cn.xsshome.mvcdo.pojo.ai.baidu.po.WordsResult;
import cn.xsshome.mvcdo.service.ai.baidu.BDOCRDetectService;
import cn.xsshome.mvcdo.util.WordConvertCodeTool;
import cn.xsshome.mvcdo.vo.BDConstant;
import cn.xsshome.mvcdo.vo.BDOCRGeneralResponse;
import com.alibaba.fastjson.JSON;
import com.baidu.aip.ocr.AipOcr;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Random;

@SuppressWarnings("ALL")
@Service("cn.xsshome.mvcdo.service.AnalysisORCTool")
public class AnalysisORCTool {
    private static Logger logger = LoggerFactory.getLogger(AnalysisORCTool.class);

    AipOcr aipOcr = BDFactory.getAipOcr();
    AipAdded aipAdded = BDFactory.getAipAdded();

    public static JSONObject tmpDev= null;
    @Autowired
    private BDOCRDetectService bdocrDetectService;


    /**
     * 根据相关参数返回数据并保存相关数据
     * @param apiType 接口类型
     * @param clientType 访问类型
     * @param dbPath 图片路径
     * @param option 具体参数
     * @param imagePath 识别图片路径
     * @return
     */
    public String getOCRResult(String apiType, String clientType, String dbPath, HashMap<String, String> option, String imagePath, String openId, String nickName) {
        String result = "";

        JSONObject jsonObject = this.getOCRJSON(apiType,imagePath, option);

        logger.info("==百度文字识别接口返回\n"+jsonObject.toString()+"end======");
        BDOCRGeneralBean bdocrGeneralBean = com.alibaba.fastjson.JSONObject.parseObject(jsonObject.toString(), BDOCRGeneralBean.class);

        BDOCRGeneralResponse bdocrGeneralResponse = new BDOCRGeneralResponse();
        bdocrGeneralResponse.setOcrType(apiType);

        BDOCRGeneralDO bdocrGeneralDO = new BDOCRGeneralDO();
        bdocrGeneralDO.setLogId(bdocrGeneralBean.getLog_id());
        bdocrGeneralDO.setOpenId(openId);
        bdocrGeneralDO.setNikeName(nickName);
        bdocrGeneralDO.setApiType(apiType);
        bdocrGeneralDO.setEnterType(clientType);
        bdocrGeneralDO.setImagePath(dbPath);

        if(null!=bdocrGeneralBean.getError_msg()||bdocrGeneralBean.getWords_result_num()==0){
            bdocrGeneralResponse.setCode(BDConstant.BD_ERROR.getCode().toString());
            if(bdocrGeneralBean.getWords_result_num()==0){
                bdocrGeneralResponse.setMsg("没有识别出文字 Sorry");
            }else{
                bdocrGeneralResponse.setMsg("服务出错了 请稍后再试");
            }
            bdocrGeneralDO.setErrorCode(bdocrGeneralBean.getError_code());
            bdocrGeneralDO.setErrorMsg(bdocrGeneralBean.getError_msg());
        }else{
            bdocrGeneralResponse.setCode(BDConstant.BD_SUCCESS.getCode().toString());
            bdocrGeneralResponse.setMsg(BDConstant.BD_SUCCESS.getMsg());
            String words = "";
            for (int i = 0; i < bdocrGeneralBean.getWords_result().size(); i++) {
                words += bdocrGeneralBean.getWords_result().get(i).getWords()+",";
            }
            words.substring(0, words.length()-1);
            bdocrGeneralResponse.setWords(words);
            bdocrGeneralResponse.setWordsesultNum(bdocrGeneralBean.getWords_result_num());
            bdocrGeneralDO.setWords(words);;
            bdocrGeneralDO.setDirection(bdocrGeneralBean.getDirection());
            bdocrGeneralDO.setWordsResultNum(bdocrGeneralBean.getWords_result_num());
            String jscode  = dealwithJScode(words,bdocrGeneralBean.getWords_result());
            bdocrGeneralResponse.setJscode(jscode);
        }
        int count = bdocrDetectService.saveOcrGeneral(bdocrGeneralDO);
        //logger.info("====保存成功了 "+count);
        result = JSON.toJSONString(bdocrGeneralResponse);

        logger.info("result:{}",result);
        return result;
    }

    private String dealwithJScode(String words, List<WordsResult> wordsResult) {
        String jscode = "";
        StringBuffer resultStr = new StringBuffer();
        if(StringUtils.isEmpty(words)) return "AI识别失败";

        List<WordsResult> listFilter = WordConvertCodeTool.filterWordsList(wordsResult);
        String firstWord = listFilter.get(0).getWords().trim();
        //过滤去掉非字母、中文、数字的其他字符的识别信息
        //firstWord = firstWord.replaceAll("[^(a-zA-Z0-9\\u4e00-\\u9fa5)]", "");
        firstWord = firstWord.replaceAll("\\(","").replaceAll("-","一");
        if(!firstWord.contains("第") && !firstWord.contains("战")  && "YES".equalsIgnoreCase(AIConstant.AUTO_MODEL)){
            //启动自动识别模式
            firstWord = "AUT1";
        }
        if(firstWord.contains("战") && firstWord.length()< "挑战二1".length() && WordConvertCodeTool.HasDigit(firstWord)){//出现 挑战1 应为挑战一1
            firstWord = firstWord.replaceAll("战","战一");
        }
        if(firstWord.length()< "挑战二1".length()  && "YES".equalsIgnoreCase(AIConstant.AUTO_MODEL)){
            //启动自动识别模式
            firstWord = "AUT1";
        }

        int idx = 1;
        try{
            if("AUT1".equals(firstWord)){//自由模式自动切
                idx = new Random().nextInt(2);
                if(idx == 0) idx = 1;
            }else{
                String tmpWord = firstWord.replaceAll("调试","");
<<<<<<< HEAD
                idx = Integer.parseInt(tmpWord.substring("挑战二".length(),tmpWord.length()));
=======
                idx = Integer.parseInt(tmpWord.substring("挑战一".length(),tmpWord.length()));
>>>>>>> e85ecf48487e32562f83aef65e913171a95da954
            }
        }catch(Exception e){
            logger.error("=dealwithJScode==firstWord{}",firstWord,e);
        }
        try {
            if(firstWord.contains("一") || firstWord.contains("-")){
                WordConvertCodeTool.convertXMLCodeOne(listFilter,resultStr);
                jscode="one-"+idx;
            }else if(firstWord.contains("二")){
                WordConvertCodeTool.convertXMLCodeOne(listFilter,resultStr);
                jscode="two-"+idx;
            }else if(firstWord.contains("三")){
                WordConvertCodeTool.convertXMLCodeOne(listFilter,resultStr);
                jscode="three-"+idx;
            }else if(firstWord.contains("四")){
                WordConvertCodeTool.convertXMLCodeFour(listFilter,resultStr);
                jscode="four-"+idx;
            }else if(firstWord.contains("五")){
                WordConvertCodeTool.convertXMLCodeFour(listFilter,resultStr);
                jscode="five-"+idx;
            }else if(firstWord.contains("六")){
                WordConvertCodeTool.convertXMLCodeFour(listFilter,resultStr);
                if(firstWord.contains("调试")) jscode = "debug"+jscode;
                jscode="six-"+idx+resultStr.toString();
            }else if(firstWord.contains("七")){
                WordConvertCodeTool.convertXMLCodeSeven(listFilter,resultStr);
                jscode="seven-"+idx;
            }else if(firstWord.contains("八")){
                WordConvertCodeTool.convertXMLCodeEight(listFilter,resultStr);
                jscode="eight-"+idx;
            }else if(firstWord.contains("九")){
                WordConvertCodeTool.convertXMLCodeNine(listFilter,resultStr);
                jscode="nine-"+idx;
            }else if(firstWord.contains("AUT")){
                WordConvertCodeTool.convertXMLCodeAuto(listFilter,resultStr);
                jscode="auto-"+idx;
<<<<<<< HEAD
=======
            }else{
                WordConvertCodeTool.convertCode(listFilter,resultStr);
>>>>>>> e85ecf48487e32562f83aef65e913171a95da954
            }

            jscode = jscode +".htmlcgjscodecgc";
            if(firstWord.contains("调试")) jscode = jscode +"debug";
            jscode = jscode + resultStr.toString();
        } catch (Exception e) {
            jscode = "auto-1.htmlcgjscodecgc";
            logger.error("===dealwithJScode===error",e);
        }

        logger.info("cg===start=dealwithJScode:{}",jscode);
        //转码 =
        jscode = jscode.replaceAll("=","ccodeg");
        logger.info("cg===end=dealwithJScode:{}",jscode);
        return jscode;
    }

    /**
     *  获取文字识别结果
     * @param apiType
     * @param imagePath
     * @param option
     * @return
     */
    private JSONObject getOCRJSON(String apiType, String imagePath, HashMap<String, String> option) {
        JSONObject jsonObject = null;
        try {
            if(tmpDev != null && "YES".equalsIgnoreCase(AIConstant.START_DEV_MEMORY)){
                return tmpDev;
            }
            if("ocr".equals(apiType)){//通用文字识别（含位置高精度版）
                jsonObject = aipOcr.accurateGeneral(imagePath, option);
                tmpDev = jsonObject;
            }else if ("ocr-1".equals(apiType)) {//通用文字识别（高精度版）
                jsonObject = aipOcr.basicAccurateGeneral(imagePath, option);
                tmpDev = jsonObject;
            }else if ("ocr-2".equals(apiType)) {//通用文字识别
                jsonObject = aipOcr.basicGeneral(imagePath, option);
                tmpDev = jsonObject;
            }else if ("ocr-3".equals(apiType)) {//通用文字识别（含位置信息版）
                jsonObject = aipOcr.general(imagePath, option);
                tmpDev = jsonObject;
            }else if (apiType.equals("bank")) {
                option.put("detect_risk", "true");
                jsonObject = aipOcr.bankcard(imagePath,option);
            }else if (apiType.equals("handwriting")) {
                jsonObject = aipAdded.handwritingDetect(imagePath, null);
            }else {
                //通用文字识别（含位置高精度版）
                jsonObject = aipOcr.accurateGeneral(imagePath, option);
                tmpDev = jsonObject;
            }
        } catch (Exception e) {
            logger.error("==getOCRJSON==error",e);
        }
        return jsonObject;
    }

}
